//
//  TopView.m
//  DaDaBao
//
//  Created by admin on 15/8/13.
//  Copyright (c) 2015年 User. All rights reserved.
//

#import "TopView.h"

@implementation TopView


- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.backgroundColor = [UIColor hexStringToColor:COLOR_VALUE];
        
    }
    return self;
}


-(void)setTitile:(NSString *)title
{
    [self setTitile:title leftEdge:44.0 rightEdge:44.0];
}

- (void)setTitile:(NSString *)title leftEdge:(CGFloat)left rightEdge:(CGFloat)right{
    UIView *labelV = [[UIView alloc] initWithFrame:CGRectMake(left, 20.0, SCREEN_WIDTH - left - right, 44.0)];
    labelV.clipsToBounds=TRUE;
    
    UILabel *titleLab = [[UILabel alloc]init];
    titleLab.backgroundColor = [UIColor clearColor];
    titleLab.font = [UIFont boldSystemFontOfSize:20.0];
    titleLab.textColor = [UIColor hexStringToColor:@"#FFFFFF"];
    titleLab.textAlignment = NSTextAlignmentCenter;
    titleLab.text = title;
    
    [labelV addSubview:titleLab];
    
    float width = [self convertToInt:titleLab.text]*18.0;
    [titleLab sizeToFit];
    
    if (width > SCREEN_WIDTH - 44.0 ) {
        
        CABasicAnimation *animation2 = [CABasicAnimation animationWithKeyPath:@"position"];
        animation2.fromValue = [NSValue valueWithCGPoint:CGPointMake(width / 2 + SCREEN_WIDTH - 44, 22.0f)];
        animation2.toValue = [NSValue valueWithCGPoint:CGPointMake(-width/2, 22.0)];
        animation2.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
        animation2.duration = width / (SCREEN_WIDTH - 88.0f)*6.0f;
        animation2.repeatCount = 999999;
        animation2.fillMode = kCAFillModeForwards;
        animation2.removedOnCompletion = FALSE;
        [titleLab.layer addAnimation:animation2 forKey:@""];
    }else
    {
        titleLab.frame = labelV.bounds;
    }
    [self addSubview:labelV];
}

-  (int)convertToInt:(NSString*)strtemp {
    
    int strlength = 0;
    char* p = (char*)[strtemp cStringUsingEncoding:NSUnicodeStringEncoding];
    for (int i=0 ; i<[strtemp lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) {
        if (*p) {
            p++;
            strlength++;
        }
        else {
            p++;
        }
    }
    return (strlength+1)/2;
    
}
@end
